//
//  QuickLoginViewController.m
//  有材网
//
//  Created by 肖扬 on 16/2/3.
//  Copyright © 2016年 肖扬. All rights reserved.
//

#import "QuickLoginViewController.h"
#import "loginModel.h"
@interface QuickLoginViewController ()<UITextFieldDelegate>{
    NSTimer *_timer;
    int timecount;
    UIButton *hqBtn;
    BOOL _isTime;
    NSDate *saveDate;
}
@property (nonatomic,strong) UITextField *accTextField;
@property (nonatomic,strong) UITextField *pwdTextField;
@end

@implementation QuickLoginViewController
@synthesize accTextField,pwdTextField;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:UIColorFromRGB(0xf2f2f2)];
    [self setView];
    [ [NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:nil];
    // Do any additional setup after loading the view.
}
-(void)textChange
{
    UIButton *loginBtn = (UIButton *)[self.view viewWithTag:12];
    if (self.accTextField.text.length ==11 && self.pwdTextField.text.length !=0) {
        if ([self.accTextField.text rangeOfString:@"**"].location == NSNotFound) {
            if (![Unity isValidateTelphone:self.accTextField.text]) {
                [loginBtn setEnabled:NO];
                return;
            }
        }
        if (![Unity isMsgCode:self.pwdTextField.text]) {
            [loginBtn setEnabled:NO];
            return;
        }
        [loginBtn setEnabled:YES];
    }else{
        [loginBtn setEnabled:NO];
    }
}
#pragma mark -- 获取验证码
-(void)getSms_code{
    TIME
    HEADDIC(nowTime, SMS_CODE);
    NSString *model = self.accTextField.text;
    if ([model rangeOfString:@"**"].location != NSNotFound) {
        model = [[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"];
    }
    NSDictionary *body = @{
                           @"mode":@"2",
                           @"mobile":model,
                           };
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:body forKey:@"body"];
    requestManage *request = [[requestManage alloc]init];
    NSString *result = [request post:APPIP postDataDic:dic error:nil];
    NSLog(@"result___%@",result);
    NSMutableDictionary *json = [result objectFromJSONString];
    if (json!=nil) {
        if ([[json objectForKey:@"err_code"] integerValue]==0) {
            saveDate = [NSDate dateWithTimeIntervalSinceNow:60];
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(verificationTime) userInfo:nil repeats:NO];
        }else{
            NSString *msg = [json objectForKey:@"err_title"];
            SHOW_TITLEALERT(@"提示", msg);
        }
    }
}

-(void)hqBtnClick{
    if (self.accTextField.text.length !=11) {
        SHOW_TITLEALERT(@"提示", @"请输入正确手机号");
        return;
    }
    if ([self.accTextField.text rangeOfString:@"**"].location == NSNotFound) {
        if (![Unity isValidateTelphone:self.accTextField.text]) {
            SHOW_TITLEALERT(@"提示", @"请输入正确手机号");
            return;
        }
    }
    [self getSms_code];
}
-(void)verificationTime{
    int time = [saveDate timeIntervalSinceNow];
    
    if (time<0)
    {
        NSString *str = [NSString stringWithFormat:@"重新发送"];
        [hqBtn setEnabled:YES];
        [hqBtn setTitle:str forState:0];
    }
    else
    {
        NSString *str = [NSString stringWithFormat:@"%ds",time];
        [hqBtn setEnabled:NO];
        [hqBtn setTitle:str forState:0];
    }
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(verificationTime) userInfo:nil repeats:NO];
}
-(void)setView{
    UIView *navView = [self createViewFrame:CGRectMake(0, 0, SWIDTH, 64) bgColor:UIColorFromRGB(0x247ac4) tag:0];
    [self.view addSubview:navView];
    [self.leftBtn setHidden:NO];
    [self.leftBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.leftBtn];
    [self.titleLab setText:self.title];
    [self.titleLab setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:self.titleLab];
    
    UIButton *btn1 = [UIButton buttonWithType:0];
    btn1.frame = CGRectMake(20, 20, 40, 44);
    [btn1 setBackgroundColor:[UIColor clearColor]];
    [btn1 addTarget:self action: @selector(backClick:) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:btn1];
    
    UIView *tempView = [self createViewFrame:CGRectMake(10, 77, SWIDTH - 20, 85) bgColor:UIColorFromRGB(0xffffff) tag:0];
    tempView.layer.masksToBounds = YES;
    tempView.layer.cornerRadius = 6.0;
    tempView.layer.borderWidth = 0.6;
    tempView.layer.borderColor = [[UIColor whiteColor] CGColor];
    [self.view addSubview:tempView];
    
    UIView *lineView = [self createViewFrame:CGRectMake(0, 42, SWIDTH-20, 0.5) bgColor:[UIColor grayColor] tag:0];
    lineView.alpha = 0.2;
    [tempView addSubview:lineView];
    UIImageView *img1 = [self createImageViewFrame:CGRectMake(15, 11, 13, 20) image:nil imageName:@"验证码" tag:0];
    [tempView addSubview:img1];
    UIImageView *img2 = [self createImageViewFrame:CGRectMake(15, 54, 13, 20) image:nil imageName:@"登录密码" tag:0];
    [tempView addSubview:img2];
    
    self.accTextField = [self createTextFieldFrame:CGRectMake(36, 0, SWIDTH - 160, 42) bgColor:[UIColor clearColor] tag:10 keyBoardType:0];
    self.accTextField.textAlignment = NSTextAlignmentLeft;
    self.accTextField.delegate = self;
    self.accTextField.placeholder = @"验证码";
    self.accTextField.font = FONT14;
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"]isEqualToString:@""]||[[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"]!=nil) {
        NSString *tel= [[[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"] stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        NSLog(@"tel:%@",tel);
        self.accTextField.text = tel;
    }
    self.accTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.accTextField.keyboardType = UIKeyboardTypeNumberPad;
    [tempView addSubview:self.accTextField];
    
    UIView *line1 = [self createViewFrame:CGRectMake(SWIDTH - 40 - 85, 11, 0.5, 20) bgColor:UIColorFromRGB(0xe8e8e8) tag:0];
    [tempView addSubview:line1];
    
    hqBtn = [UIButton buttonWithType:0];
    hqBtn.frame = CGRectMake(SWIDTH - 122, 9, 80, 24);
    [hqBtn setTitle:@"获取验证码" forState:0];
    [hqBtn setBackgroundColor:[UIColor clearColor]];
    [hqBtn setTitleColor:BLUEColor forState:0];
    [tempView addSubview:hqBtn];
    hqBtn.clipsToBounds = YES;
    hqBtn.layer.cornerRadius = 5.0f;
    [hqBtn addTarget:self action:@selector(hqBtnClick) forControlEvents:7];
    hqBtn.titleLabel.font = FONT14;
    
    self.pwdTextField = [self createTextFieldFrame:CGRectMake(36, 43, SWIDTH - 53, 42) bgColor:[UIColor clearColor] tag:11 keyBoardType:0];
    self.pwdTextField.textAlignment = NSTextAlignmentLeft;
    self.pwdTextField.delegate = self;
    self.pwdTextField.placeholder = @"密码";
    self.pwdTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.pwdTextField.font = FONT14;
    [tempView addSubview:self.pwdTextField];
    self.accTextField.placeholder = @"手机号";
    self.pwdTextField.placeholder = @"验证码";
    img1.image = [UIImage imageNamed:@"登录-手机icon"];
    img2.image = [UIImage imageNamed:@"验证码"];
    
    UIButton *loginBtn = [self createButtonFrame:CGRectMake(10, 177, SWIDTH - 20, 43) title:@"快捷登录" viewController:self selector:@selector(submit:) tag:12];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.titleLabel.font = FONT14;
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"登录-点击后按钮"] forState:UIControlStateNormal];
    [self.view addSubview:loginBtn];
    [loginBtn setEnabled:NO];
    
    if (self.accTextField.text.length !=0) {
        [self.pwdTextField becomeFirstResponder];
    }else{
        [self.accTextField becomeFirstResponder];
    }
}

#pragma mark -- 登录
-(void)submit:(UIButton *)sender{
    if ([self.accTextField.text rangeOfString:@"**"].location == NSNotFound) {
        if (![Unity isValidateTelphone:self.accTextField.text]) {
            SHOW_TITLEALERT(@"提示", @"请输入正确手机号");
            return;
        }
    }
    if (![Unity isMsgCode:self.pwdTextField.text]) {
        SHOW_TITLEALERT(@"提示", @"验证码有误");
        return;
    }
    [self requestLogin];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.accTextField) {
        if ([string isEqualToString:@""]) {
            NSString *acc = self.accTextField.text;
            if ([acc rangeOfString:@"**"].location != NSNotFound) {
                self.accTextField.text = @"";
            }
        }
    }
    return YES;
}

-(void)requestLogin{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *mobile = self.accTextField.text;
    if ([self.accTextField.text rangeOfString:@"**"].location != NSNotFound) {
        mobile = [[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"];
    }
    BODYDIC(@"2", mobile, self.pwdTextField.text);
    TIME
    HEADDIC(nowTime,LOGIN);
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:BODY forKey:@"body"];
    requestManage *request = [[requestManage alloc]init];
    NSError *error;
    NSString *result = [request post:APPIP postDataDic:dic error:&error];
    NSLog(@"result__%@",result);
    if (result!=nil || ![result isEqualToString:@""]) {
        loginModel *loginInfo = [[loginModel alloc]init];
        [loginInfo parseResponseData:result];
        if ([loginInfo.err_code integerValue]==0) {
            loginModelObj *model = [loginInfo.data objectForKey:@"userInfo"];
            [[NSUserDefaults standardUserDefaults] setObject:model.certificate forKey:@"certificate"];
            [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isLogin"];
            [[NSUserDefaults standardUserDefaults] setObject:model.nickname forKey:@"nickname"];
            //                [[NSUserDefaults standardUserDefaults] setObject:model forKey:@"userInfo1"];
            if ([self.accTextField.text rangeOfString:@"**"].location == NSNotFound) {
                [[NSUserDefaults standardUserDefaults] setObject:self.accTextField.text forKey:@"userIphone"];
            }
            [[NSUserDefaults standardUserDefaults] setObject:self.pwdTextField.text forKey:@"userPwd"];
            [[NSUserDefaults standardUserDefaults] setObject:self.pwdTextField.text forKey:@"newpassword"];
            [appStatus shareAppStatus].loginSuccess = @"1";
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}

-(void)backClick:(UIButton *)sender{
    dispatch_async(dispatch_get_main_queue(), ^{
        _isTime = NO;
        [self.navigationController popViewControllerAnimated:YES];
    });
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 110) {
        if (buttonIndex == 1) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
